<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/1/9
 * Time: 13:00
 */


$w = new weixinSdk();
$accessToken = $w->getAccessToken();
if(isset($_GET["echostr"]) &&!empty($_GET["echostr"])){
    $w->valid(true);
}

if($w->valid()){
    $data = file_get_contents("php://input");
    file_put_contents('1.xml', $data);
    $data=xmlHandle::xml2array($data);
    $myOpenId = $data['ToUserName'];
    $customOpenId = $data['FromUserName'];
    $data['FromUserName'] = $myOpenId;
    $data['ToUserName'] = $customOpenId;
    $data['Content'] .='?';
    $data['CreateTime'] = time();
    $xml = xmlHandle::xml_encode($data);
    echo $xml;
    file_put_contents('2.xml',$xml);
}


class weixinSdk
{
    public $token;
    public $appid;
    public $secret;

    public function __construct(){
        $this->token = "eirwiorweioruiwerwelk";
        $this->appid = 'wx6da7cc3a7f88b680';
        $this->secret = '3ecd2b80ec6f3c666e75d87fac1502d7';
    }

    public function getAccessToken(){
        $file = $this->get();
        if($file){
            $j = json_decode($file ,true);
            if(time()<$j['time']){
                return  $j['accessToken'];
            }
        }

        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->secret;
        if($data = file_get_contents($url)){
            if(!$data){
                return false;
            }
            $json = json_decode($data ,true);
            if(!$json){
                return false;
            }
            if($json['errcode']){
                return [$json['errcode'],$json['errmsg']];
            }
            $result = [
                'time' => time() + $json['expires_in'],
                'accessToken' =>$json['access_token'],
            ];
            $this->set($result);
            return $result['accessToken'];
        }
    }

    public function get(){
        $file = dirname(__FILE__).'/'.md5('access');
        return file_exists($file)?file_get_contents($file):false;
    }

    public function set($result){
        $file = dirname(__FILE__).'/'.md5('access');
        if(file_exists($file)){
            chmod($file, 0777);
        }
        return file_put_contents($file, json_encode($result),LOCK_EX);
    }

    public function valid($return=false)
    {
        if($this->checkSignature()){
            if($return){
                echo  $_GET["echostr"];exit;
            }
            return true;
        }
        return false;
    }
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        
        $nonce = $_GET["nonce"];
        $token = $this->token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr ,SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            $error = print_r($_GET,true)."\ntoken:".$token."\ntmpStr".$tmpStr."\nsign:".$signature;
            file_put_contents('error.txt',$error);
            return false;
        }
    }

}




class xmlHandle
{
    public static function xml2array($str){
        return (array)simplexml_load_string($str,SimpleXMLElement,LIBXML_NOCDATA);
    }

    public static function xmlSafeStr($str)
    {
        return '<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';
    }

    public static function data_to_xml($data) {
        $xml = '';
        foreach ($data as $key => $val) {
            is_numeric($key) && $key = "item id=\"$key\"";
            $xml    .=  "<$key>";
            $xml    .=  ( is_array($val) || is_object($val)) ? self::data_to_xml($val)  : self::xmlSafeStr($val);
            list($key, ) = explode(' ', $key);
            $xml    .=  "</$key>";
        }
        return $xml;
    }

    public static function xml_encode($data, $root='xml', $item='item', $attr='', $id='id', $encoding='utf-8') {
        if(is_array($attr)){
            $_attr = array();
            foreach ($attr as $key => $value) {
                $_attr[] = "{$key}=\"{$value}\"";
            }
            $attr = implode(' ', $_attr);
        }
        $attr   = trim($attr);
        $attr   = empty($attr) ? '' : " {$attr}";
        $xml   = "<{$root}{$attr}>";
        $xml   .= self::data_to_xml($data, $item, $id);
        $xml   .= "</{$root}>";
        return $xml;
    }

    public static function post($url, $postdata = null){
        $ch = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_POST, 1);//POST方式
        curl_setopt($ch,CURLOPT_POSTFIELDS, $postdata);//POST数据
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

}

